package com.ys.erp.stage_shop_service.service;

import com.alibaba.fastjson2.JSONObject;
import com.ys.erp.common.enums.EnableEnum;
import org.apache.commons.lang3.ObjectUtils;
import com.ys.erp.entity.data.bean.ShopExt;
import com.ys.erp.entity.service.IEventLogService;
import com.ys.erp.entity.service.IShopExtService;
import com.ys.erp.framework.bean.dto.StageEmpDTO;
import com.ys.erp.framework.exception.YsException;
import com.ys.erp.stage_shop_service.bean.condition.ShopCondition;
import com.ys.erp.stage_shop_service.bean.vo.ZfbSeparateAccountSettingVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * @author minamiyama
 * @date 2025/6/18
 */
@Service
@RequiredArgsConstructor
public class ShopService {

    private final IShopExtService shopExtService;

    private final IEventLogService iEventLogService;

    /**
     * 更新店铺支付宝分账设置
     *
     * @param con 更新参数
     */
    public void updateZfbSeparateAccountSetting(StageEmpDTO empDto, ShopCondition.UpdateZfbSeparateAccountCon con) {
        // 根据店铺编码查询店铺扩展信息
        ShopExt shopExt = shopExtService.getByCode(con.getShopCode());
        if (shopExt == null) {
            throw new YsException(10003, "店铺不存在");
        }
        // 更新支付宝分账相关信息
        shopExt.setZfbAccount(con.getZfbAccount());
        shopExt.setZfbSeparateRatio(con.getZfbSeparateRatio());
        shopExt.setIsOpenZfbSeparateAccount(con.getIsOpenZfbSeparateAccount());
        shopExt.setZfbName(con.getZfbName());
        // 保存更新
        shopExtService.updateById(shopExt);
        String jsonString = JSONObject.toJSONString(con);
        iEventLogService.insertEvent(empDto, "更新店铺支付宝分账设置, 参数" + con.getShopCode(), shopExt.getId(), EnableEnum.NO.getEnable(), jsonString);
    }

    /**
     * 查询店铺支付宝分账设置
     *
     * @param shopCode 店铺编码
     * @return 分账设置信息
     */
    public ZfbSeparateAccountSettingVO getZfbSeparateAccountSetting(String shopCode) {
        // 根据店铺编码查询店铺扩展信息
        ShopExt shopExt = shopExtService.getByCode(shopCode);
        if (ObjectUtils.isEmpty(shopExt)) {
            throw new YsException(10003, "店铺不存在");
        }
        // 转换为VO并返回
        return new ZfbSeparateAccountSettingVO()
                .setZfbAccount(shopExt.getZfbAccount())
                .setZfbSeparateRatio(shopExt.getZfbSeparateRatio())
                .setZfbName(shopExt.getZfbName())
                .setIsOpenZfbSeparateAccount(shopExt.getIsOpenZfbSeparateAccount());
    }
}